package org.jsbd.boss.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsbd.boss.common.DataGridModel;
import org.jsbd.boss.dao.IBaseInfoDAO;
import org.jsbd.boss.dao.IUserBaseCanDoLogDao;
import org.jsbd.boss.domian.BaseInfo;
import org.jsbd.boss.domian.WbUserBaseCanDoLog;
import org.jsbd.boss.service.IUserBaseCanDoLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

@Service("userBaseCanDoLogService")
public class UserBaseCanDoLogServiceImpl implements IUserBaseCanDoLogService {

	@Autowired
	private IUserBaseCanDoLogDao userBaseCanDoLogDao;

	@Autowired
	private IBaseInfoDAO baseInfoDAO;

	@Override
	public Map<String, Object> getListPage(DataGridModel page, WbUserBaseCanDoLog log) {

		log = (log == null ? new WbUserBaseCanDoLog() : log);
		log.setPageInfo(page);
		Map<String, Object> results = new HashMap<String, Object>();
		results.put("total", userBaseCanDoLogDao.getListPageCount(log));

		List<WbUserBaseCanDoLog> list = (List<WbUserBaseCanDoLog>) userBaseCanDoLogDao.getList(log);

		for (WbUserBaseCanDoLog doLog : list) {
			JSONObject obj = JSONObject.parseObject(doLog.getData());
			Integer total = 0;
			if (log.getBase() != null && log.getBase().length() > 0) {
				if (obj.containsKey(log.getBase())) {
					total = obj.getInteger(log.getBase());
				}
			} else {
				for (Map.Entry<String, Object> entry : obj.entrySet()) {
					total += Integer.valueOf(entry.getValue().toString());
				}
			}
			doLog.setTotal(total);
		}

		results.put("rows", list);
		return results;
	}

	@Override
	public List<WbUserBaseCanDoLog> getById(Long id, String base) {
		WbUserBaseCanDoLog log = userBaseCanDoLogDao.getById(id);

		List<BaseInfo> bases = baseInfoDAO.getAllChannelInfo();
		HashMap<String, String> map = new HashMap<>(bases.size());
		for (BaseInfo baseInfo : bases) {
			map.put(baseInfo.getId(), baseInfo.getBaseName());
		}

		JSONObject obj = JSONObject.parseObject(log.getData());

		List<WbUserBaseCanDoLog> list = new ArrayList<>();
		if (base != null && base.length() > 0) {
			if (obj.containsKey(base)) {
				WbUserBaseCanDoLog doLog = new WbUserBaseCanDoLog();
				doLog.setBase(base);
				doLog.setCount(obj.getString(base));
				String name = map.get(base);
				doLog.setBaseName(name);
				list.add(doLog);
			}
		} else {
			for (Map.Entry<String, Object> entry : obj.entrySet()) {
				WbUserBaseCanDoLog doLog = new WbUserBaseCanDoLog();
				doLog.setBase(entry.getKey());

				String name = map.get(entry.getKey());
				doLog.setBaseName(name);

				doLog.setCount(entry.getValue().toString());
				list.add(doLog);
			}
		}

		return list;
	}

}
